import axios from "axios";
import { message } from 'antd';
import store from 'store2'
// 创建axios实例对象
const instance = axios.create({
    // 判断环境变量是否为开发环境
    baseURL: process.env.NODE_ENV === 'development' ? 'https://mock.apifox.cn/m1/2597364-0-default' : 'https://mock.apifox.cn/m1/2597364-0-default'
})
// 请求拦截器
instance.interceptors.request.use(config => {
    config.headers.token = store.get('users')?.token
    return config
})
// 响应拦截器
instance.interceptors.response.use(response => {
    if (response.data.code === '10119') {
        message.error(response.data.message)
        setTimeout(() => {
            store.remove('users')
            window.location.href = '/login'
        }, 1000)
    } else {

        message.open({
            type: response.data.code === '200' ? 'success' : 'error',
            content: response.data.message
        })
        return response
    }
})

// 后续借助这个request请求实现get/post相关的接口调用
export default function request(config) {
    const { url = '', method = 'GET', data = {}, headers = {} } = config
    switch (method.toUpperCase()) {
        case 'GET':
            return instance.get(url, { params: data })
        case 'POST':
            // 如果是表单提交
            if (headers['content-type'] === 'application/x-www-form-url-encoded') {
                const p = new URLSearchParams()
                for (const key in data) {
                    p.append(key, data[key])
                }
                return instance.post(url, p, { headers })
            }
            // 如果是文件提交
            if (headers['content-type'] === 'multipart/form-data') {
                const p = new FormData()
                for (const key in data) {
                    p.append(key, data[key])
                }
                return instance.post(url, p, { headers })
            }
            // 否则就是 application/json的形式
            return instance.post(url, data)
        default:
            return instance(config)
    }
}